home *** CD-ROM | disk | FTP | other *** search
/ The X-Philes (2nd Revision) / The X-Philes Number 1 (1995).iso / xphiles / hp48hor2 / asc2bin6.c < prev    next >
C/C++ Source or Header  |  1991-11-22  |  2KB  |  84 lines

  1. /* ASC2BIN - v 1.1 Detlef Mueller '91 - 
  2.    Usage: ASC2BIN < [input file] > [output file] 
  3. */
  4.  
  5. #include    <stdio.h>
  6. #include    <stdlib.h>
  7. #include    <ctype.h>
  8.  
  9. #include    <io.h>                /* MesS-DOS */
  10. #include    <fcntl.h>            /* MesS-DOS */
  11.  
  12. #define    MAXDTA    32766                /* MesS-DOS */
  13.  
  14. static void Error ( int f, char *err )
  15. {
  16.     fprintf( stderr,"\n%s\n", err ) ;
  17.  
  18.     if ( f )
  19.     exit( -1 ) ;
  20. }
  21.  
  22. static void PutNibb ( int nibb )
  23. {
  24.     static unsigned char
  25.     in[MAXDTA],            /* Input buffer */
  26.     *p = in ;            /* Pointer to input buffer */
  27.     static unsigned
  28.     crc = 0,            /* CRC value */
  29.     len = 0 ;            /* Count of nibbles in buffer */
  30.  
  31.     if ( nibb == -1 )            /* Flush input buffer */
  32.     {
  33.     if ( len <= 4 )
  34.         Error( 1, "Invalid string" ) ;
  35.  
  36.     if ( crc )
  37.         Error( 0, "CRC error !!! Be carefull ..." ) ;
  38.  
  39.     if ( len & 1 )
  40.         *(p - 2) &= 0x0F ;        /* Mask out 1st CRC nibble */
  41.  
  42.     printf( "HPHP48-E" ) ;        /* Binary download header */
  43.                     /* Flush input buffer to stdout */
  44.     for ( p = in, nibb = (len - 3) >> 1 ; nibb ; --nibb, ++p )
  45.         putc( *p, stdout ) ;
  46.  
  47.     return ;
  48.     }
  49.  
  50.     if ( ++len & 1 )
  51.     *p = nibb ;
  52.     else
  53.     *p++ |= nibb << 4 ;
  54.  
  55.     if ( len > MAXDTA )            /* Input to big .. */
  56.     Error( 1, "File to big ..." ) ;
  57.  
  58.     nibb = (crc ^ nibb) & 0x0F ;    /* Update CRC value */
  59.     crc  = (crc >> 4) ^ (nibb | (nibb << 7) | (nibb << 12)) ;
  60. }
  61.  
  62. void main ( void )
  63. {
  64.     int
  65.     i ;
  66.  
  67.     setmode( fileno( stdout ), O_BINARY ) ;    /* MesS-DOS */
  68.  
  69.     while ( (i = getc( stdin )) != '"' ) /* Search for start of str */
  70.     if ( i == EOF )
  71.         Error( 1, "No data found" ) ;
  72.  
  73.     while ( (i = getc( stdin )) != '"' )
  74.     if ( isxdigit( i ) )        /* Is hex-digit */
  75.         PutNibb( i - (i > '9' ? '7' : '0') ) ;
  76.     else
  77.     if ( i == EOF )
  78.         Error( 1, "Unexpected EOF" ) ;
  79.  
  80.     PutNibb( -1 ) ;            /* Flush input buffer */
  81.  
  82.     exit( 0 ) ;
  83. }
  84.